<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class AuthMethod
{
    public function handle(Request $request, Closure $next): Response
    {
        // 跨域
        if (in_array($request->method(), ['POST', 'PUT', 'PATCH'])) {
            $contentType = $request->header('Content-Type');
            if (strpos($contentType, 'application/json') === false) {
                return \response()->json([
                    'message' => 'Content-Type must be application/json',
                ] , Response::HTTP_UNSUPPORTED_MEDIA_TYPE);
            }

        }

        $response = $next($request);

        if (!$response->headers->has('Content-Type')) {
            $response->headers->set('Content-Type', 'application/json');
        }

        return $response;
    }
}
